package com.bolt.auth.security.common.converter;

import com.bolt.auth.security.common.constant.SecurityConstants;
import com.bolt.auth.security.common.model.AuthUserDetails;
import com.bolt.common.utils.JacksonUtil;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2020/12/3.
 */
public class CustomTokenEnhancer implements TokenEnhancer {

    public CustomTokenEnhancer() {

    }
    /**
     * 自定义一些token属性
     * @param accessToken
     * @param authentication
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        final Map<String, Object> additionalInformation = new HashMap<>(16);
        if (authentication.getOAuth2Request().isRefresh()) {
            Map<String, Object> map = decode(accessToken.getRefreshToken().getValue());
            if (map.containsKey("accountOpenCode")) {
                additionalInformation.put("accountOpenCode", map.get("accountOpenCode"));
            }
            if (map.containsKey("grantType")) {
                additionalInformation.put("grantType", map.get("grantType"));
            }
            if (map.containsKey("sub")) {
                additionalInformation.put("sub", map.get("sub"));
            } else {
                additionalInformation.put("sub", authentication.getUserAuthentication().getName());
            }
        }else{
            // Important !,client_credentials mode ,no user!
            if (authentication.getUserAuthentication() != null) {
                AuthUserDetails userDetails =  (AuthUserDetails)authentication.getUserAuthentication().getPrincipal();
                additionalInformation.put(SecurityConstants.DETAILS_USER_ID, userDetails.getUserId());
                additionalInformation.put(SecurityConstants.DETAILS_USERNAME, userDetails.getUsername());
                additionalInformation.put(SecurityConstants.DETAILS_DEPT_ID, "");
                additionalInformation.put(SecurityConstants.DETAILS_CLIENT_ID, userDetails.getClientId());
            }
        }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
        return accessToken;
    }

    protected Map<String, Object> decode(String token) {
        try {
            Jwt jwt = JwtHelper.decode(token);
            String claimsStr = jwt.getClaims();
            Map<String, Object> claims = JacksonUtil.toMap(claimsStr);
            return claims;
        } catch (Exception e) {
            throw new InvalidTokenException("Cannot convert access token to JSON", e);
        }
    }
}

 